package com.qfedu.knowledge.aspect;

import com.qfedu.knowledge.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName DistributedLock
 * @Author ykx
 * @Date 2024/6/1 18:54
 * @Version 1.0
 */
@Component
@Aspect
@Slf4j
public class DistributedLock {

    @Autowired
    private RedisUtils redisUtils;

    @Pointcut("execution(* com.qfedu.knowledge.job.*.*(..))")
    public void pointCut() {

    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint jp) throws Throwable {
        // 方法执行前的操作
        Object ob = null;
        if (redisUtils.setnx(jp.getSignature().getName(), jp.getSignature().getName(), 300L)) {
            //调用原方法
            log.info(jp.getSignature().getName() + ":获取分布式锁成功，执行定时任务");
            ob = jp.proceed();
        } else {
            log.info(jp.getSignature().getName() + ":获取分布式锁失败");
        }

        // 方法执行后的操作:释放锁
        log.info(jp.getSignature().getName() + ":执行完毕，释放资源");
        redisUtils.delete(jp.getSignature().getName());

        return ob;
    }

}
